package cn.leedsoft.and.crimeintent.controller.crime_intent;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import cn.leedsoft.and.crimeintent.common.PictureUtil;
import cn.leedsoft.and.crimeintent.R;
import cn.leedsoft.and.crimeintent.model.Crime;
import cn.leedsoft.and.crimeintent.model.CrimeLab;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * A placeholder fragment containing a simple view.
 */
public class CrimeDetailFragment extends Fragment {
    public static final String TAG = "CrimeDetailFragment";
    private Crime mCrime;
    private EditText mTitle;
    private Button mDateButton;
    private CheckBox mSolvedCheckBox;
    private ImageButton mImageButton;
    private ImageView mImageView;
    private PictureUtil mPictureUtil;
    private Button mBtnReport;
    private Button mBtnSuspect;
    public static final String INTENT_KEY_CRIME_ID = "intent.key.crime.id";
    public static final int REQ_CODE_DATE_DIALOG = 0;
    private static final int REQ_CODE_CAMERA_PIC = 1;
    private static final int REQ_CODE_CONTACT = 2;

    public static CrimeDetailFragment newInstance(UUID uuid) {
        Bundle args = new Bundle();
        args.putSerializable(INTENT_KEY_CRIME_ID, uuid);

        CrimeDetailFragment fragment = new CrimeDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            if (NavUtils.getParentActivityName(getActivity()) != null) {
                getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
            }
            Log.d(TAG, "当前parent：" + NavUtils.getParentActivityName(getActivity()));
        }
        setHasOptionsMenu(true);

        UUID uuid = (UUID) getArguments().getSerializable(INTENT_KEY_CRIME_ID);
        if (uuid != null) {
            mCrime = CrimeLab.getInstance(getActivity()).get(uuid);
        }
        if (mCrime == null) mCrime = new Crime();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (NavUtils.getParentActivityName(getActivity()) != null) {
                    NavUtils.navigateUpFromSameTask(getActivity());
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);

        mTitle = (EditText) view.findViewById(R.id.crime_title);
        mTitle.setText(mCrime.getTitle());
        mTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCrime.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mDateButton = (Button) view.findViewById(R.id.crime_date);
        mDateButton.setText(String.format("%tF", mCrime.getDate()));
//        mDateButton.setEnabled(false);
        mDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//启动新的fragment//设置target fragment，其实是给予新的fragment，父fragment的引用。从而手动调用父fragment的onActivityResult，统一监听fragment回调
                DetailDateDialogFragment dialogFragment = DetailDateDialogFragment.newInstance(mCrime.getDate());
                dialogFragment.setTargetFragment(CrimeDetailFragment.this, REQ_CODE_DATE_DIALOG);
                dialogFragment.show(getActivity().getSupportFragmentManager(), DetailDateDialogFragment.TAG);

            }
        });

        mSolvedCheckBox = (CheckBox) view.findViewById(R.id.crime_solved);
        mSolvedCheckBox.setChecked(mCrime.isSolved());
        mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mCrime.setSolved(isChecked);
            }
        });

        mImageButton = (ImageButton) view.findViewById(R.id.imgbtn_head);
        mImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), CrimeCameraActivity.class);
//                startActivityForResult(intent, REQ_CODE_CAMERA_PIC);
                Intent intent = new Intent();//使用隐式intent，启动系统相机，拍照。
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri uri = getOutputUri();
                mCrime.setPicUri(uri.getPath());
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//系统默认保存
                startActivityForResult(intent, REQ_CODE_CAMERA_PIC);
            }
        });
        PackageManager packageManager = getActivity().getPackageManager();
        boolean hasCamera = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
                || packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
        if (!hasCamera) {
            mImageButton.setEnabled(false);
        }

        mImageView = (ImageView) view.findViewById(R.id.imgview_head_ic);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageDialogFragment.newInstance(mCrime.getPicUri()).show(getActivity().getSupportFragmentManager(), ImageDialogFragment.TAG);
            }
        });

        mPictureUtil = new PictureUtil(getActivity());

        mBtnSuspect = (Button) view.findViewById(R.id.btn_suspect);
        if (mCrime.getSuspectName() != null) mBtnSuspect.setText(mCrime.getSuspectName());
        mBtnSuspect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //intent action
                intent.setAction(Intent.ACTION_GET_CONTENT);
                //intent type 返回数据的mime type
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                startActivityForResult(intent, REQ_CODE_CONTACT);
            }
        });
        mBtnReport = (Button) view.findViewById(R.id.btn_report);
        mBtnReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCrime.getSuspectPhone() == null) {
                    Toast.makeText(getActivity(), "请先选择联系人", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, "哈喽订单点点滴滴");
                intent = Intent.createChooser(intent, "发送哈哈");
                startActivity(intent);

            }
        });
        return view;
    }

    private Uri getOutputUri() {
        File picFile = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), UUID.randomUUID().toString() + ".jpg");
        return Uri.fromFile(picFile);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) return;
        switch (requestCode) {
            case REQ_CODE_DATE_DIALOG:
                Date date = (Date) data.getSerializableExtra(DetailDateDialogFragment.INTENT_KEY_CRIME_DATE);
                mCrime.setDate(date);
                mDateButton.setText(String.format("%tF", mCrime.getDate()));
                break;
            case REQ_CODE_CAMERA_PIC:
                if(data == null) {
                    Log.d(TAG, "data IS null, file saved on target position. image saved to: " + mCrime.getPicUri());
                    mPictureUtil.showPic(mImageView, mCrime.getPicUri());
                }
                break;
            case REQ_CODE_CONTACT:
                Uri uri = data.getData();
                String[] queryFields = {
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                };

                Cursor cursor = getActivity().getContentResolver().query(uri, queryFields, null, null, null);

                if (cursor.getCount() == 0) {
                    cursor.close();
                    return;
                }
                cursor.moveToFirst();
                mCrime.setSuspectName(cursor.getString(0));
                mCrime.setSuspectPhone(cursor.getString(1));
                mBtnSuspect.setText(mCrime.getSuspectName());

                cursor.close();
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mPictureUtil.showPic(mImageView, mCrime.getPicUri());
    }

    @Override
    public void onStop() {
        super.onStop();
        mPictureUtil.clearPic(mImageView);
    }
}
